package com.ruoyi.bean.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.ruoyi.bean.service.CaptchaService;
import com.ruoyi.common.constants.CacheConstants;
import com.ruoyi.common.result.Result;
import com.ruoyi.common.util.RandomCharUtil;
import com.ruoyi.common.util.UUIdUtils;
import com.ruoyi.domain.CaptchaVo;
import io.github.stylesmile.annotation.AutoWired;
import io.github.stylesmile.annotation.Controller;
import io.github.stylesmile.annotation.RequestMapping;
import io.github.stylesmile.server.Response;
import io.github.stylesmile.tool.PropertyUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@Controller
public class CaptchaController {
    @AutoWired
    private DefaultKaptcha defaultKaptcha;

    @AutoWired
    private CaptchaService captchaService;

    /**
     * 生成验证码
     */
    @RequestMapping("/auth/code")
    public Result<CaptchaVo> authCode() throws IOException {
        // 保存验证码信息
        String uuid = UUIdUtils.simpleUUID();

        String code2 = RandomCharUtil.generateRandomString(4);
        BufferedImage image = defaultKaptcha.createImage(code2);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        baos.flush();
        byte[] imageBytes = baos.toByteArray();
        baos.close();
//        String captchaBase64 = "data:image/png;base64," + java.util.Base64.getEncoder().encodeToString(imageBytes);
        String captchaBase64 = java.util.Base64.getEncoder().encodeToString(imageBytes);

        CaptchaVo captchaVo = new CaptchaVo();
        captchaVo.setUuid(uuid);
        captchaVo.setImg(captchaBase64);
        return Result.ok(captchaVo);
    }
}
